<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学校" prop="schoolID">
        <el-select v-model="queryParams.schoolID">
          <el-option v-for="item in school_name" :key="item.value" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="年级" prop="gradeID">
        <el-input v-model="queryParams.gradeID" placeholder="请输入年级" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <div class="top">
      <el-button type="primary" icon="Plus" @click="() => { addKjFlag = true }">新增</el-button>
      <el-button type="warning" plain icon="upload" @click="handleImport">导入</el-button>
    </div>

    <!-- 动态渲染多个表格，每个学校和年级一个表格 -->
    <div v-for="(group, schoolGrade ) in groupedBySchoolGradeAll" :key="schoolGrade" class="school-grade-table">
      <h3>{{ schoolGrade }}</h3>
      <el-table border v-loading="loading" :data="group" row-key="parentIndicatorId" :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column label="一级指标" prop="category" />
        <el-table-column label="指标等级" align="center" prop="level" width="80" />
        <el-table-column label="指标名称" align="center" prop="description" show-overflow-tooltip />
        <el-table-column label="权重" align="center" prop="weight" width="80" />
        <el-table-column label="学校" prop="schoolID" align="center" />
        <el-table-column label="年级" align="center" prop="gradeID" width="80" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)"
              v-hasPermi="['indicator:indicator:edit']">修改</el-button>
            <el-button link type="primary" @click="handleAdd(scope.row)" v-hasPermi="['indicator:indicator:add']"
              v-if="scope.row.level != 3">新增</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['indicator:indicator:remove']"
              v-if="scope.row.level != 1">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>


  <!-- 弹窗 -->
  <el-dialog v-model="dialogTableVisible" title="修改信息" width="300">
    <div>
      <el-input v-model="formData.description" placeholder="请输入新的指标名称" style="margin-bottom: 10px;"></el-input>
      <el-input v-model="formData.weight" type="number" placeholder="请输入权重信息"></el-input>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>

  <!-- 弹窗新增指标模板 -->
  <el-dialog v-model="addKjFlag" title="新增指标模板" width="400">
    <el-form :model="addKjDate" ref="addKjDateRef" :inline="true" label-width="68px">
      <el-form-item label="学校" prop="SchoolName">
        <el-select v-model="addKjDate.schoolName">
          <el-option v-for="item in school_name" :key="item.value" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="入学年份" prop="grade">
        <el-input v-model="addKjDate.grade" placeholder="请输入年级" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addIndactors">新增</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>


  <!-- 弹窗新增信息 -->
  <el-dialog v-model="addIndactorFlag" title="新增下级指标" width="400">
    <el-form :model="addIndactorsdate1" :inline="true" label-width="100px">
      <el-form-item label="所属类目" prop="category">
        <el-input v-model="addIndactorsdate1.category" :disabled="true" />
      </el-form-item>
      <el-form-item label="上级指标id" prop="description">
        <el-input v-model="addIndactorsdate1.parentIndicatorId" :disabled="true" />
      </el-form-item>
      <el-form-item label="等级" prop="description">
        <el-input v-model="addIndactorsdate1.level" :disabled="true" />
      </el-form-item>
      <el-form-item label="指标id" prop="treeCode">
        <el-input v-model="addIndactorsdate1.treeCode" placeholder="请输入年级" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="addIndactorsdate1.description" placeholder="请输入指标名称" />
      </el-form-item>
      <el-form-item label="权重" prop="weight">
        <el-input v-model="addIndactorsdate1.weight" placeholder="请输入权重信息" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addIndactors1">新增</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>


  <!-- 上传文件 -->
  <el-dialog v-model="daoru" title="导入数据" width="400">
    <uploadIndactors :message="groupedBySchoolGradeAll" @submit_success="submitSuccess" />
  </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, onMounted, reactive, toRefs } from 'vue';
import { listIndicator, updateIndicator, addIndicator, delIndicator } from "@/api/indicator/indicator";
const showSearch = ref(true);
const loading = ref(false);  // 控制加载状态
const isExpandAll = ref(false);  // 控制是否展开所有树节点
const groupedBySchoolGradeAll = ref({});  // 存储按学校和年级分组的数据
const groupedBySchoolGrade = ref({});  // 存储按学校和年级分组的数据
const dialogTableVisible = ref(false);
const data = reactive({
  queryParams: {
    schoolID: null,
    gradeID: null,
    category: null,
    level: null,
    parentIndicatorId: null,
    description: null,
    treeCode: null,
    orderNum: null,
    weight: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    schoolID: [{ required: true, message: "学校不能为空", trigger: "blur" }],
    gradeID: [{ required: true, message: "年级不能为空", trigger: "blur" }],
    category: [{ required: true, message: "指标不能为空", trigger: "blur" }],
    level: [{ required: true, message: "水平不能为空", trigger: "blur" }],
    description: [{ required: true, message: "指标名称不能为空", trigger: "blur" }],
    treeCode: [{ required: true, message: "树编码不能为空", trigger: "blur" }]
  },
  formData: {}
});

// 组件通信
function submitSuccess() {
  daoru.value = false;
  getList();
}

const { queryParams, formData } = toRefs(data);
const { proxy } = getCurrentInstance();
const { grade_name, class_name, school_name } = proxy.useDict('grade_name', 'class_name', 'school_name');

// 获取指标列表
function getList() {
  loading.value = true;
  listIndicator(queryParams.value).then(response => {
    loading.value = false;
    if (response.code === 200) {
      const data = response.data;
      const grouped = groupBySchoolGrade(data);

      // 将按学校和年级分组的数据存入 groupedBySchoolGrade
      groupedBySchoolGradeAll.value = grouped;
      groupedBySchoolGrade.value = grouped;
    }
  });
}

// 根据学校和年级分组数据
function groupBySchoolGrade(data) {
  const groupedData = {};

  data.forEach(item => {
    const schoolName = `学校：${item.schoolID}`; // 替换为实际学校名称映射（如果有）
    const gradeName = `年级：${new Date().getFullYear() - item.gradeID + 1}年级`;  // 替换为实际年级名称映射（如果有） 
    const schoolGrade = `${schoolName}，${gradeName}`; // 分组键

    if (!groupedData[schoolGrade]) {
      groupedData[schoolGrade] = [];
    }

    // 增加 `schoolName` 和 `gradeName` 到每个数据项
    groupedData[schoolGrade].push({
      ...item,
      schoolName,
      gradeName
    });
  });

  // 对每组数据进行树形处理
  Object.keys(groupedData).forEach(schoolGrade => {
    groupedData[schoolGrade] = buildTree(groupedData[schoolGrade]);
  });

  return groupedData;
}



// 构建树形结构
function buildTree(data) {
  const map = {};
  const result = [];

  // 将数据映射为 treeCode -> item 的形式
  data.forEach(item => {
    map[item.treeCode] = { ...item, children: [] };
  });

  // 将子项按 parentIndicatorId 分组到对应的父项下
  data.forEach(item => {
    if (item.parentIndicatorId) {
      if (map[item.parentIndicatorId]) {
        map[item.parentIndicatorId].children.push(map[item.treeCode]);
      }
    } else {
      result.push(map[item.treeCode]);
    }
  });

  return result;
}

// 修改操作
function handleUpdate(row) {
  const data = {}
  data.indicatorId = row.indicatorId
  data.level = row.level
  // console.log('Update:', data);
  const lever = row.level
  if (lever == 1) {
    ElMessageBox.prompt('请输入你要修改的权重', '修改', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^[0-9]+$/, // 匹配非负整数
      inputErrorMessage: '请输入有效的整数',
    })
      .then(({ value }) => {
        // 将输入值转换为整数
        const weight = parseInt(value, 10);
        // 判断是否为有效整数
        if (isNaN(weight)) {
          ElMessage({
            type: 'error',
            message: '输入的值无效',
          });
          return;
        }

        // 发送信息
        data.weight = weight
        updateIndicator(data).then(res => {
          console.log(res);
          if (res.code == 200) {
            ElMessage({
              type: 'success',
              message: `已成功修改权重为：${weight}`,
            });
          }
          getList()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '修改已取消',
        });
      });

  } else if (lever == 2 || lever == 3) {
    formData.value.indicatorId = row.indicatorId
    formData.value.description = row.description
    formData.value.weight = row.weight
    dialogTableVisible.value = true
  }
}

function handleSubmit() {
  updateIndicator(formData.value).then(res => {
    console.log(res);
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: '修改成功'
      });
      resetQuery()
    }
    getList()
  })
}

// 新增操作
const addIndactorsdate1 = ref({})
const addIndactorFlag = ref(false);
function handleAdd(row) {
  console.log('Add:', row);
  addIndactorFlag.value = true
  addIndactorsdate1.value.level = row.level + 1
  addIndactorsdate1.value.category = row.category
  addIndactorsdate1.value.gradeID = row.gradeID
  addIndactorsdate1.value.schoolID = row.schoolID
  addIndactorsdate1.value.parentIndicatorId = row.treeCode
}

function addIndactors1() {
  const list = addIndactorsdate1.value.treeCode.split('.')
  const temp = list.slice(0, list.length - 1).join(".");
  if (temp !== addIndactorsdate1.value.parentIndicatorId) {
    ElMessage({
      type: 'error',
      message: '指标id格式错误',
    });
    return
  }

  addIndicator(addIndactorsdate1.value).then(res => {
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: '新增成功',
      });
    } else {
      ElMessage({
        type: 'error',
        message: '新增失败',
      });
    }
    queryParams.value = {
      schoolID: addIndactorsdate1.value.schoolID,
      gradeID: addIndactorsdate1.value.gradeID
    }
    getList();
    addIndactorFlag.value = false
  })
}
// 删除操作
function handleDelete(row) {
  const description = row.description
  ElMessageBox.confirm('是否确认删除指标为"' + description + '"的数据项？').then({
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    const children = row.children
    if (children.length) {
      ElMessage({
        type: 'error',
        message: '存在下级指标不可删除',
      });
      return
    }
    const indicatorId = row.indicatorId
    delIndicator(indicatorId).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        queryParams.value = {
          schoolID: row.schoolID,
          gradeID: row.gradeID
        }
        getList();
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '删除已取消',
    });
  })
}


/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dialogTableVisible.value = false
  queryParams.value = {}
  formData.value = {}
  handleQuery();
}

// 新增框架
const addKjFlag = ref(false);
const addKjDate = ref({});

// 新增信息
function addIndactors() {

  const schoolName = `学校：${addKjDate.value.schoolName}`;
  const gradeName = `年级：${new Date().getFullYear() - addKjDate.value.grade + 1}年级`;
  const schoolGrade = `${schoolName}，${gradeName}`;
  if (schoolGrade in groupedBySchoolGradeAll.value) {
    ElMessage({
      type: 'error',
      message: '该年级已存在指标，请勿重复添加',
    });
    return
  }
  const data = [
    { schoolID: addKjDate.value.schoolName, gradeID: addKjDate.value.grade, category: "德育", level: 1, description: "德育", treeCode: "1", weight: 1 },
    { schoolID: addKjDate.value.schoolName, gradeID: addKjDate.value.grade, category: "智育", level: 1, description: "智育", treeCode: "2", weight: 1 },
    { schoolID: addKjDate.value.schoolName, gradeID: addKjDate.value.grade, category: "体育", level: 1, description: "体育", treeCode: "3", weight: 1 },
    { schoolID: addKjDate.value.schoolName, gradeID: addKjDate.value.grade, category: "美育", level: 1, description: "美育", treeCode: "4", weight: 1 },
    { schoolID: addKjDate.value.schoolName, gradeID: addKjDate.value.grade, category: "劳育", level: 1, description: "劳育", treeCode: "5", weight: 1 }
  ]
  const flag = true
  data.forEach(item => {
    addIndicator(item).then(res => {
      if (res.code !== 200) flag = false
    })
  })

  if (flag) {
    queryParams.value.schoolID = addKjDate.value.schoolName
    queryParams.value.gradeID = addKjDate.value.grade
    getList()
    addKjFlag.value = false
    ElMessage({
      type: 'success',
      message: '新增成功,请继续添加'
    });
  }
}
// 页面加载时获取数据
onMounted(() => {
  getList();
});

import uploadIndactors from '@/views/tool/uploadVue/uploadIndactors.vue'
const daoru = ref(false)
function handleImport() {
  daoru.value = true
}
</script>

<style scoped>
.top {
  margin: 20px;
}

.el-table {
  margin-top: 20px;
}

.el-table-column__label {
  font-weight: bold;
}

.school-grade-table {
  margin-bottom: 40px;
}
</style>
